#!/usr/bin/python
import urllib
import urllib2
from xml.dom import minidom

from commons import yconfig, gconfig, youtrack_login
from proyectos import projects

def delete_req(resource):
    url = yconfig.url + resource
    req = urllib2.Request(url, None, {'Content-Length': '0'})
    req.get_method = lambda: 'DELETE'
    handle = urllib2.urlopen(req)
    return handle

def find(resource, find_nodes, process_node):
    url = yconfig.url + resource
    result = set()
    def find_page(start=0):
        r = urllib2.urlopen('%s?start=%s' % (url, start)).read()
        xml = minidom.parseString(r)
        nodes = find_nodes(xml)
        if nodes:
            for n in nodes:
                result.add(process_node(n))
            return find_page(start+1)
        else:
            return result
    return find_page()

find_users = lambda: find('/rest/admin/user/', lambda xml: xml.childNodes[0].childNodes, lambda n: n.getAttribute('login'))
find_groups = lambda: find('/rest/admin/group/', lambda xml: xml.childNodes[0].childNodes, lambda n: n.getAttribute('name'))

def delete_project(projectId):
    return delete_req('/rest/admin/project/%s' % projectId)

def delete_user(user):
    if user not in ['root', yconfig.login, 'guest']:
        delete_req('/rest/admin/user/%s' % urllib.quote(user))

def delete_users():
    for user in find_users():
        delete_user(user)

def main():
    youtrack_login()
    for projectId, project in enumerate(projects, 1):
        print ("Borrando proyecto %s..." % project['name'])
        delete_project(str(projectId))
    delete_users()

if __name__ == "__main__":
    main()
